﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

[System.Serializable]
public class RainbowPopRecoDat
{
    public int user_id;
    public int popcount_oneday;
    public int popdays_continuesly;
    public long lastPopTime;
    public bool isFMDownloaded;
}

public class GiftBagResManager : MonoSingleton<GiftBagResManager> {

    const string key_rainbow_lastOpen_time = "key_lastOpen_time";
    const string iamge_basepath = "SuperwingsImage";
    public const string url_apk = "http://download.caihongfm.cn/caihong.apk";
    public const string url_popImage = "http://page.soulgame.mobi/superwings/fm/fm.png";

    public RainbowPopRecoDat popdat;

    protected override void Init()
    {
        base.Init();

        popdat = new RainbowPopRecoDat();
        PopRadioViewRecord();

        if (!FileTools.IsDirectoryExist(ResPath))
            FileTools.CreateDirectory(ResPath);

        EventBus.Instance.AddEventHandler<string>(EventID.SDK_DOWNLOADFINISHED, OnDownloadFinished);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        EventBus.Instance.RemoveEventHandler<string>(EventID.SDK_DOWNLOADFINISHED, OnDownloadFinished);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.H))
            PlayerPrefs.DeleteKey(key_rainbow_lastOpen_time);
        if (Input.GetKeyDown(KeyCode.V))
            IsRainbowAppDownlaod = !IsRainbowAppDownlaod;
    }

    #region 彩虹电台弹窗控制

    public bool IsRainbowAppDownlaod
    {
        get {
            return popdat.isFMDownloaded;
        }
        set {
            popdat.isFMDownloaded = value;
            SavePopReco();
        }
    }

    //记录弹窗事件
    public void PopRadioViewRecord()
    {
        if (PlayerPrefs.HasKey(key_rainbow_lastOpen_time))
        {
            LoadPopReco();
            DateTime curTime = TimeUtils.CurTime;
            DateTime lastPopTime = TimeUtils.ToDateTime(popdat.lastPopTime);
            Debug.Log("curTime: " + curTime + " lastTime: " + lastPopTime);

            if (TimeUtils.IsSameDay(lastPopTime, curTime))
            {
                popdat.popcount_oneday++;
            }
            else
            {
                popdat.popdays_continuesly++;
                popdat.popcount_oneday = 0;
            }
        }
        else
        {
            popdat.popcount_oneday = 1;
            popdat.popdays_continuesly = 1;

        }

        SavePopReco();
    }

    public bool IsNeedPopRadioView()
    {
        return !(popdat.popcount_oneday > 3 || popdat.popdays_continuesly > 3 || popdat.isFMDownloaded);
    }


    public void SavePopReco()
    {
        popdat.user_id = UserManager.Instance.UserId;
        popdat.lastPopTime = TimeUtils.CurUnixTime;

        string jstr = JsonUtility.ToJson(popdat);
        PlayerPrefs.SetString(key_rainbow_lastOpen_time, jstr);

        Debug.LogError("oneday: " + popdat.popcount_oneday + " cont: " + popdat.popdays_continuesly);
    }

    public void LoadPopReco()
    {
        string jstr = PlayerPrefs.GetString(key_rainbow_lastOpen_time);
        popdat = JsonUtility.FromJson<RainbowPopRecoDat>(jstr);
    }

    #endregion

    #region 彩虹电台弹窗图片下载

    public void DownloadRadioImage(Action<Texture2D> onsuccess, Action<string> onerror)
    {
        string filename = FileTools.GetFullName(url_popImage);

        DownloadTask task = new DownloadTask();
        task.URL = url_popImage;
        task.SavePath = FileTools.CombinePaths(ResPath, filename);
        task.OnSuccess = () =>
        {
            //Debug.Log(task.SavePath);
            LoadTexture(task.SavePath, onsuccess);
        };
        task.OnError = (errstr) =>
        {
            //Debug.Log(errstr);
            onerror(errstr);
        };
        DownloadManager.Instance.AddTask(task);
    }

    public void LoadTexture(string fullpath, Action<Texture2D> callback)
    {
        StartCoroutine(LoadTextureIEnumator(fullpath, callback));
    }

    private IEnumerator LoadTextureIEnumator(string fullpath, Action<Texture2D> callback)
    {
        WWW www = new WWW("file:///" + fullpath);
        yield return www;

        if (callback != null)
            callback(www.texture);
    }


    #endregion

    public string ResPath
    {
        get {
            return FileTools.CombinePath(Application.persistentDataPath, iamge_basepath);
        }
    }

    private void OnDownloadFinished(string url)
    {
        if (url == url_apk)
        {
            Debug.Log("apk下载成功");
            IsRainbowAppDownlaod = true;
        }
    }
}
